package com.renl.juc.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static java.lang.Thread.sleep;

/**
 * @author renl
 * @date 2020/1/7
 */
class MyCache{
  private volatile Map<String,Object> map = new HashMap<>();
  private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

  public void put(String key,String value){
    rwLock.writeLock().lock();
    System.out.println(Thread.currentThread().getName() + "\t 开始写入缓存....");
    try {
      sleep(300);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
      map.put(key,value);
      System.out.println(Thread.currentThread().getName() + "\t 写入完成..." );
      rwLock.writeLock().unlock();
    }
  }
  public void get(String key){
    rwLock.readLock().lock();
      System.out.println(Thread.currentThread().getName() + "\t 开始读取缓存....");
      try {
        sleep(300);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }finally {
        Object o = map.get(key);
//        System.out.println(o);
        System.out.println(Thread.currentThread().getName() + "\t 读取缓存完成....");
        rwLock.readLock().unlock();
      }

  }
}
public class ReadWriteLockDemo {
  public static void main(String[] args) {
    MyCache myCache = new MyCache();
    for (int i = 0 ; i < 5 ; i++){
      final int interInt = i;
      new Thread(() -> {
        myCache.put(interInt + "" , interInt + "a");
      },i + "" ).start();
      new Thread(() -> {
        myCache.get(interInt + "");
        },i + "" ).start();
    }
  }
}
